package com.osdp.gateway.filter;

import com.osdp.gateway.util.CommonConstant;
import com.osdp.gateway.util.TokenHolder;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;
/**
 * 将token存放在ThreadLocal中，请求处理完后，清除token
 */
@Configuration
public class TokenFilter implements WebFilter {
    /**
     * 从cookie中取token
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, HttpCookie> cookieMap = request.getCookies();
        HttpCookie httpCookie = cookieMap.getFirst(CommonConstant.HEADER_ACCESS_TOKEN);
        String token = null;
        if(httpCookie != null){
            token = httpCookie.getValue();
        }
        if(token == null){
            List<String> cookics = request.getHeaders().get(CommonConstant.HEADER_ACCESS_TOKEN);
            if(!CollectionUtils.isEmpty(cookics)){
                token = cookics.get(0);
            }
        }
        TokenHolder.setToken(token);
        return chain.filter(exchange).doFinally(e-> TokenHolder.removeToken());
    }
}
